<template>
    <div class="common-container">
        <el-row class="top-actions" :gutter="10">
            <el-col :span="12" class="left-actions">
                <el-button type="success" @click="handleAdd" :disabled="newPlanPermission">
                    <el-icon>
                        <Plus />
                    </el-icon>新增
                </el-button>
            </el-col>
            <el-col :span="12" class="right-actions">
                <el-button type="default" @click="handleRefresh">
                    <el-icon>
                        <Refresh />
                    </el-icon>
                    刷新
                </el-button>
            </el-col>
        </el-row>
        <div class="table-scroll-container">
            <el-table :data="tableData" stripe border style="width: 100%" v-loading="loading">
                <el-table-column label="编号" width="180">
                    <template #default="scope">
                        ZX{{ scope.row.updatedAt.split("-").join("").replace(" ", "").split(":").join("") }}
                    </template>
                </el-table-column>
                <el-table-column prop="status" label="状态" width="100" />
                <el-table-column prop="name" label="名称" width="180" />
                <el-table-column label="期限" width="220">
                    <template #default="scope">
                        {{ formatDeadline(scope.row.startAt, scope.row.endAt) }}
                    </template>
                </el-table-column>
                <el-table-column prop="type" label="类型" width="100">
                    <template #default="scope">
                        {{ convertDict("专项计划类型", "v2l", scope.row.type) }}
                    </template>
                </el-table-column>
                <el-table-column prop="responsibleName" label="责任单位" width="160" />
                <el-table-column prop="remark" label="描述" min-width="200" :show-overflow-tooltip="{
                    popperClass: 'overflow-tooltip',
                }" />
                <el-table-column prop="leaderName" label="牵头人" width="100"></el-table-column>
                <el-table-column label="操作" width="160">
                    <template #default="scope">
                        <el-button size="small" type="primary" @click="handleAssign(scope.row)"
                            :disabled="scope.row.leaderName != ''">指派</el-button>
                        <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>

                    </template>
                </el-table-column>
            </el-table>
        </div>
        <el-dialog v-model="addDialogVisible" title="新增专项数据" width="900px" :before-close="handleDialogClose"
            v-if="addDialogVisible" :close-on-click-modal="false">
            <el-form ref="addFormRef" :model="addForm" :rules="addFormRules" label-width="100px"
                :validate-on-rule-change="false">
                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="名称" prop="name">
                            <el-input v-model="addForm.name" placeholder="请输入名称" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="类型" prop="type">
                            <el-select v-model="addForm.type" placeholder="选择类型">
                                <el-option v-for="type in getTypeOptions()" :label="type.label" :value="type.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="责任单位" prop="responsibleId">
                            <el-select v-model="addForm.responsibleId" placeholder="选择责任单位"
                                @change="getSubstationOptions()">
                                <el-option label="四号线变电维护工班" value="ed9a74bc-edc8-40ba-a294-f28c97e3d04a" />
                                <el-option label="六号线变电参建工班" value="abf16776-a784-4e69-ae77-dee317b05bdd" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="16">
                        <el-form-item label="专项期限" prop="start2End">
                            <el-date-picker v-model="addForm.start2End" type="daterange" range-separator="至"
                                start-placeholder="开始日期" end-placeholder="结束日期" @change="handleDateRangeChange" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="16">
                        <el-form-item label="变电所" prop="substationList">
                            <el-select v-model="addForm.substationList" :placeholder="substationPlaceholder" clearable
                                multiple filterable collapse-tags :collapse-tags-tooltip="true" :max-collapse-tags="3"
                                style="width: 100%;" :disabled="!substationList.length > 0"
                                @change="handleSubstationChange">
                                <template #header>
                                    <el-checkbox v-model="substationCheckAll" :indeterminate="substationIndeterminate"
                                        @change="handleSubstationCheckAll">
                                        选择全部
                                    </el-checkbox>
                                </template>
                                <el-option v-for="(item, index) in substationList" :key="item.id" :label="item.name"
                                    :value="item.id" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="系统" prop="systemId">
                            <el-select v-model="addForm.systemId" :placeholder="systemPlaceholder" clearable filterable
                                :disabled="!systemList.length > 0" @change="handleSystemChange">
                                <el-option v-for="(item, index) in systemList" :key="item.id" :label="item.name"
                                    :value="item.id" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="16">
                        <el-form-item label="设备" prop="equipmentList">
                            <el-select v-model="addForm.equipmentList" :placeholder="equipmentPlaceholder" clearable
                                multiple filterable collapse-tags :collapse-tags-tooltip="true" :max-collapse-tags="3"
                                style="width: 100%;" :disabled="!equipmentList.length > 0"
                                @change="handleEquipmentChange">
                                <template #header>
                                    <el-checkbox v-model="equipmentCheckAll" :indeterminate="equipmentIndeterminate"
                                        @change="handleEquipmentCheckAll">
                                        选择全部
                                    </el-checkbox>
                                </template>
                                <el-option v-for="(item, index) in equipmentList" :key="item.id" :label="item.name"
                                    :value="item.id" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="16">
                        <el-form-item label="最小单元" prop="unit">
                            <el-input-tag v-model="addForm.unitList" placeholder="请输入最小单元后按回车" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="需求类型" prop="requirement">
                            <el-select v-model="addForm.requirementTemp" placeholder="选择需求类型"
                                @change="handleRequirementChange">
                                <el-option label="图片" value="图片" />
                                <el-option label="数据" value="数据" />
                                <el-option label="图片、数据" value="图片、数据" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="数据组数" prop="dataGroupCount">
                            <el-input v-model.number="addForm.dataGroupCount" type="number" min="1"
                                placeholder="请输入数据组数" :disabled="isDataNeed" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="16">
                        <el-form-item label="字段" prop="dataFields">
                            <el-input-tag v-model="addForm.dataFields" placeholder="请输入数据字段后按回车"
                                :disabled="isDataNeed" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="描述" prop="remark">
                            <el-input v-model="addForm.remark" type="textarea" :rows="4" placeholder="请输入该专项的详细描述文字" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="专项文件" prop="planFileIds">
                            <el-upload v-model:file-list="planFileList" :action="`${baseURL}/sys/file/upload`"
                                :headers="{ Authorization: 'Bearer ' + cookies.get('token') }" multiple
                                class="upload-file">
                                <el-button type="primary">点击上传</el-button>
                            </el-upload>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <el-button @click="handleDialogClose">取消</el-button>
                <el-button type="primary" @click="handleSubmit" :loading="submitLoading">确定</el-button>
            </template>
        </el-dialog>
        <el-dialog v-model="assignDialogVisible" title="专项计划指派" width="600px" :before-close="handleDialogClose"
            :close-on-click-modal="false" v-if="assignDialogVisible">
            <el-form ref="assignFormRef" :model="assignForm" :rules="assignFormRules" label-width="100px"
                :validate-on-rule-change="false">

                <el-row :gutter="20">
                    <el-col :span="24">
                        <el-form-item label="牵头人" prop="leaderId">
                            <UserSelector ref="userSelectorRef" @fillUser="fillUser"></UserSelector>
                        </el-form-item>

                    </el-col>
                </el-row>


                <el-row :gutter="20">
                    <el-col :span="24">
                        <el-form-item label="任务附件" prop="taskFileIds">
                            <el-upload v-model:file-list="taskFileList" :action="`${baseURL}/sys/file/upload`"
                                :headers="{ Authorization: 'Bearer ' + cookies.get('token') }" multiple
                                class="upload-file">
                                <el-button type="primary">点击上传</el-button>
                            </el-upload>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>


            <template #footer>
                <el-button @click="handleDialogClose">取消</el-button>
                <el-button type="primary" @click="handleAssignSubmit" :loading="submitLoading">确定</el-button>
            </template>
        </el-dialog>
        <div class="pagination-container">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="currentPage" :page-sizes="[15, 30, 45, 60, 100]" :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper" :total="total" />
        </div>
    </div>
</template>
<script setup>
import { ref, onMounted, nextTick, watch, computed } from 'vue';
import { Plus, Refresh } from '@element-plus/icons-vue';
import { convertDict } from '@/utils/Misc.js';
import { formatDeadline } from '@/utils/Format.js';
import zxlzAPI from '@/api/zxlz.js';
import optionsAPI from '@/api/options.js';
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import UserSelector from '@/components/UserSelector.vue';
import { errorNotify } from '@/utils/Misc';
import { useCookies } from 'vue3-cookies';
const { cookies } = useCookies();
import useStore from '@/store/index';
const store = useStore();
const baseURL = import.meta.env.VITE_API_BASE_URL
const substationList = ref([]);
const systemList = ref([]);
const equipmentList = ref([]);
const tableData = ref([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(15);
const total = ref(0);
const addDialogVisible = ref(false);
const assignDialogVisible = ref(false);
const addFormRef = ref(null);
const userSelectorRef = ref(null);
const equipmentCheckAll = ref(false);
const equipmentIndeterminate = ref(false);
const substationCheckAll = ref(false);
const substationIndeterminate = ref(false);
const submitLoading = ref(false);
const planFileList = ref([]);
const taskFileList = ref([]);
const lineId = ref("");
const substationPlaceholder = ref("请先选择责任单位")
const systemPlaceholder = ref("请先选择变电所")
const equipmentPlaceholder = ref("请先选择系统")
const addForm = ref({
    name: '',
    type: '',
    start2End: [],
    startAt: '',
    endAt: '',
    responsibleId: "",
    systemId: "",
    substationList: [],
    substationIds: "",
    equipmentList: [],
    equipmentIds: "",
    unitList: [],
    unit: "",
    requirementTemp: "",
    requirement: {},
    dataGroupCount: null,
    dataFields: [],
    remark: "",
});
const addFormRules = ref({
    name: [
        { required: true, message: '请输入名称', trigger: 'blur' }
    ],
    start2End: [
        { required: true, message: '请选择起止时间', trigger: 'change' }
    ],
    type: [
        { required: true, message: '请选择类型', trigger: 'change' }
    ],
    responsibleId: [
        { required: true, message: '请选择责任单位', trigger: 'change' }
    ],
    substationList: [
        { required: true, message: '请选择变电站名称', trigger: 'change' }
    ],
    systemId: [
        { required: true, message: '请选择系统名称', trigger: 'change' }
    ],
    equipmentList: [
        { required: true, message: '请选择设备名称', trigger: 'change' }
    ],
    requirement: [
        { required: true, message: '请选择需求类型', trigger: 'change' }
    ],
    dataGroupCount: [
        { required: true, message: '请填写数据组数', trigger: 'blur' }
    ],
    dataFields: [
        { required: true, message: '请填写数据字段数', trigger: 'blur' }
    ],
    remark: [
        { required: true, message: '请填写备注', trigger: 'blur' }
    ],
});
const assignFormRules = ref({
    leaderId: [
        { required: true, message: '请选择牵头人', trigger: 'change' }
    ],
    taskFileIds: [
        { required: true, message: '请上传任务附件', trigger: 'change' }
    ]
});
const newPlanPermission = computed(() => {
    return !store.user.roleNames.includes("技术管理")
})
const assignFormRef = ref(null);
const assignForm = ref({
    leaderId: "",
    taskFileIds: "",
    id: ""
});
const isDataNeed = computed(() => {
    return !addForm.value.requirementTemp.includes('数据')
})
watch(
    () => addForm.value.equipmentList,
    (newVal) => {
        if (!newVal || newVal.length === 0) {
            equipmentCheckAll.value = false;
            equipmentIndeterminate.value = false;
        }
        else if (newVal.length === equipmentList.value.length) {
            equipmentCheckAll.value = true;
            equipmentIndeterminate.value = false;
        }
        else {
            equipmentCheckAll.value = false;
            equipmentIndeterminate.value = true;
        }
    },
    { immediate: true }
);
const fillUser = (data) => {
    assignForm.value.leaderId = data;
};
const getSubstationOptions = () => {
    const responsibleId = addForm.value.responsibleId
    if (responsibleId == "ed9a74bc-edc8-40ba-a294-f28c97e3d04a") {
        lineId.value = "620a7464-5238-4b88-a3ed-a1fa34d2e2a1"
    } else if (responsibleId == "abf16776-a784-4e69-ae77-dee317b05bdd")
        lineId.value = "367ccf6f-7379-4f17-986f-8c3539b7268b"
    substationPlaceholder.value = "加载中..."
    optionsAPI.getSubstation(lineId.value).then(res => {
        substationList.value = res.data.tree.locationTree
        substationPlaceholder.value = "请选择变电所"
    })
}
const handleSubstationChange = () => {
    if (addForm.value.substationList.length == 0) {
        addForm.value.substationIds = ""
        addForm.value.systemId = ""
        systemList.value = []
        systemPlaceholder.value = "请先选择变电所"
        return
    }
    addForm.value.substationIds = addForm.value.substationList.join(",")
    systemPlaceholder.value = "加载中..."
    getSystemOptions()
}
const getSystemOptions = () => {
    optionsAPI.getSystem().then(res => {
        systemList.value = res.data.page.list
        systemPlaceholder.value = "请选择系统"
    })
}
const handleSystemChange = () => {
    if (addForm.value.systemId == undefined) {
        addForm.value.equipmentIds = ""
        equipmentList.value = []
        equipmentPlaceholder.value = "请先选择系统"
        return
    }
    equipmentPlaceholder.value = "加载中..."
    getEquipmentOptions()
}
const getEquipmentOptions = () => {
    optionsAPI.getEquipment(lineId.value, addForm.value.systemId).then(res => {
        equipmentList.value = res.data.page.list
        if (equipmentList.value.length == 0) {
            equipmentPlaceholder.value = "该系统下无设备或加载失败"
        } else {
            equipmentPlaceholder.value = "请选择设备"
        }
    })
}
const handleEquipmentChange = () => {
    addForm.value.equipmentIds = addForm.value.equipmentList.join(",")
}
const getTypeOptions = () => {
    const planTypeDict = store.dict.find(item => item.name === '专项计划类型');
    if (!planTypeDict?.children) {
        console.warn('未找到专项计划类型字典数据');
        return [];
    }
    return planTypeDict.children
        .slice()
        .sort((a, b) => a.label.localeCompare(b.label, 'zh-CN'))
        .map(item => ({
            label: item.label,
            value: item.value
        }));
};
const handleEquipmentCheckAll = (checked) => {
    if (checked) {
        addForm.value.equipmentList = equipmentList.value.map(item => item.id);
        equipmentIndeterminate.value = false;
    } else {
        addForm.value.equipmentList = [];
        equipmentIndeterminate.value = false;
    }
};
watch(
    () => addForm.value.substationList,
    (newVal) => {
        if (!newVal || newVal.length === 0) {
            substationCheckAll.value = false;
            substationIndeterminate.value = false;
        }
        else if (newVal.length === substationList.value.length) {
            substationCheckAll.value = true;
            substationIndeterminate.value = false;
        }
        else {
            substationCheckAll.value = false;
            substationIndeterminate.value = true;
        }
    },
    { immediate: true }
);
const handleSubstationCheckAll = (checked) => {
    if (checked) {
        addForm.value.substationList = substationList.value.map(item => item.id);
        substationIndeterminate.value = false;
    } else {
        addForm.value.substationList = [];
        substationIndeterminate.value = false;
    }
    handleSubstationChange()
};
const handleRequirementChange = (value) => {
    addForm.value.requirement = value;
    if (value.includes('数据')) {
        addFormRules.value.dataGroupCount[0].required = true;
        addFormRules.value.dataFields[0].required = true;
    } else {
        addFormRules.value.dataGroupCount[0].required = false;
        addFormRules.value.dataFields[0].required = false;
    }
    nextTick(() => {
        addFormRef.value?.clearValidate(['dataGroupCount', 'dataFields']);
    });
};
const handleDateRangeChange = (dateRange) => {
    if (dateRange && dateRange.length === 2) {
        addForm.value.startAt = formatDate(dateRange[0]);
        addForm.value.endAt = formatDate(dateRange[1]);
    } else {
        addForm.value.startAt = '';
        addForm.value.endAt = '';
    }
};
const formatDate = (date) => {
    if (!date) return '';
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day} `;
};
const fetchData = () => {
    loading.value = true;
    let responsibleId = store.user.departmentId
    if (store.user.roleNames.includes("技术管理") || store.user.roleNames.includes("主任")) {
        responsibleId = ''
    }
    const params = {
        responsibleId: responsibleId,
        pageDto: {
            pageNo: currentPage.value,
            pageSize: pageSize.value,
            orderBy: 'updated_at desc'
        },
    };
    zxlzAPI.list(params).then((res) => {
        tableData.value = res.data.page.list.map(item => {
            return {
                ...item,
                status: convertDict("专项计划状态", "v2l", item.status),
            };
        });
        total.value = res.data?.page?.count;
        loading.value = false;
    }).catch((error) => {
        errorNotify("ZhuangXiang.vue", "fetchData", error);
        total.value = 100;
        loading.value = false;
    });
};
onMounted(() => {
    fetchData();
});
const handleAdd = () => {
    addDialogVisible.value = true;
    nextTick(() => {
        resetFormData()
    });
};
const handleDialogClose = () => {
    addDialogVisible.value = false;
    assignDialogVisible.value = false
    nextTick(() => {
        resetFormData()
    });
};
const handleSubmit = () => {
    addFormRef.value.validate((valid) => {
        if (valid) {
            submitLoading.value = true;
            addForm.value.requirement = JSON.stringify({
                type: addForm.value.requirementTemp,
                count: addForm.value.dataGroupCount,
                field: addForm.value.dataFields,
            });
            addForm.value.substationIds = addForm.value.substationList.join(",");
            addForm.value.equipmentIds = addForm.value.equipmentList.join(",");
            addForm.value.unit = addForm.value.unitList.join(",");
            addForm.value.planFileIds = planFileList.value.map((item) => item.response.sysFile.id).join(",");
            zxlzAPI.create(addForm.value).then((res) => {
                submitLoading.value = false;
                ElMessage.success('新增成功');
                handleDialogClose();
                handleRefresh();
                resetFormData();
            }).catch((error) => {
                errorNotify("ZhuangXiang.vue", "handleSubmit", error);
                submitLoading.value = false;
            });
        } else {
            return false;
        }
    });
};
const handleAssignSubmit = () => {
    // 验证任务附件是否已上传
    if (taskFileList.value.length === 0) {
        ElMessage.warning('请上传任务附件');
        return;
    }

    assignFormRef.value.validate((valid) => {
        if (valid) {
            submitLoading.value = true;
            assignForm.value.taskFileIds = taskFileList.value.map((item) => item.response.sysFile.id).join(",");
            zxlzAPI.setLeader(assignForm.value).then((res) => {
                submitLoading.value = false;
                ElMessage.success('指派成功');
                handleDialogClose();
                handleRefresh();
                resetFormData();
            }).catch((error) => {
                errorNotify("ZhuangXiang.vue", "handleAssignSubmit", error);
                submitLoading.value = false;
            });
        } else {
            return false;
        }
    });
};
const resetFormData = () => {
    addForm.value = {
        name: '',
        type: '',
        start2End: [],
        startAt: '',
        endAt: '',
        responsibleId: "",
        systemId: "",
        substationList: [],
        substationIds: "",
        equipmentList: [],
        equipmentIds: "",
        unitList: [],
        unit: "",
        requirementTemp: "",
        requirement: {},
        dataGroupCount: 1,
        dataFields: [],
        remark: "",
        planFileIds: ""
    };
    assignForm.value = {
        id: "",
        taskFileIds: "",
        leaderId: "",
    };
    planFileList.value = [];
    taskFileList.value = [];
    substationCheckAll.value = false;
    substationIndeterminate.value = false;
    equipmentCheckAll.value = false;
    equipmentIndeterminate.value = false;
    substationPlaceholder.value = "请先选择责任单位";
    systemPlaceholder.value = "请先选择变电所";
    equipmentPlaceholder.value = "请先选择系统";
    substationList.value = [];
    systemList.value = [];
    equipmentList.value = [];
};
const handleRefresh = () => {
    fetchData();
};
const handleAssign = (row) => {
    assignForm.value.id = row.id;
    assignDialogVisible.value = true
};
const handleDelete = (row) => {
    ElMessageBox.confirm('将永久删除【' + row.name + '】专项, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    }).then(() => {
        const loading = ElLoading.service({
            lock: true,
            text: '正在删除专项...',
            background: 'rgba(0, 0, 0, 0.7)'
        });
        zxlzAPI.delete(row.id).then((res) => {
            ElMessage.success("删除成功");
            fetchData();
        }).catch((error) => {
            errorNotify("ZhuangXiang.vue", "handleDelete", error);
        }).finally(() => {
            loading.close();
        });
    });
};
const handleSizeChange = (val) => {
    pageSize.value = val;
    fetchData();
};
const handleCurrentChange = (val) => {
    currentPage.value = val;
    fetchData();
};

</script>
<style scoped>
:deep(.overflow-tooltip) {
    width: 30%;
    font-size: 13px !important;
    border-radius: 4px !important;
    padding: 8px 12px !important;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15) !important;
}

.upload-file :deep(.el-upload-list) {
    max-height: 100px;
    overflow-y: auto;
    overflow-x: hidden;
    margin-top: 8px;
    padding: 4px 0;
}

.common-container {
    padding: 20px;
    background-color: #fff;
    border-radius: 4px;
    max-height: calc(100vh - 40px);
    display: flex;
    flex-direction: column;
}

.top-actions {
    margin-bottom: 20px;
    align-items: center;
}

.left-actions {
    text-align: left;
}

.right-actions {
    text-align: right;
}

.table-scroll-container {
    flex: 1;
    overflow-y: auto;
    margin-bottom: 20px;
    max-height: calc(100vh - 290px);
}

.table-scroll-container::-webkit-scrollbar {
    width: 8px;
    height: 8px;
}

.table-scroll-container::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 4px;
}

.table-scroll-container::-webkit-scrollbar-thumb {
    background: #c1c1c1;
    border-radius: 4px;
}

.table-scroll-container::-webkit-scrollbar-thumb:hover {
    background: #a8a8a8;
}

.pagination-container {
    margin-top: auto;
    padding-top: 10px;
    display: flex;
    justify-content: flex-end;
    position: sticky;
    bottom: 0;
    background-color: #fff;
    z-index: 10;
}


.upload-file {
    width: 50%;
    text-align: left;
}

.upload-file el-button {
    display: inline-block;
    margin-left: 0;
}
</style>
